package
{
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.media.Sound;
	import flash.net.URLRequest;
	import flash.utils.Dictionary;
	import flash.utils.Timer;

	public class SoundManager
	{
		private static var m_readySounds:Object = new Object;
		private static var m_sounds:Object = new Object;
		private static var m_urlBySound:Dictionary = new Dictionary(true);
		private static var m_cooldownReady:Boolean = true;
		private static var m_cooldownTimer:Timer = new Timer(100);
		public function SoundManager()
		{

		}
		
		public static function init():void{
			var i:int, il:int;
			var sounds:Array = new Array();
			
			m_cooldownTimer.addEventListener(TimerEvent.TIMER, onCooldownUp);
			
			
			sounds.push('assets/mouseOver.mp3');
			sounds.push('assets/mouseOver2.mp3');
			sounds.push('assets/click.mp3');
			sounds.push('assets/buyStore.mp3');
			sounds.push('assets/error.mp3');
			sounds.push('assets/cheer.mp3');

			for(i = 0, il = sounds.length; i < il; i++){
				var sound:Sound = new Sound(new URLRequest(sounds[i]));
				m_urlBySound[sound] = sounds[i];
				sound.addEventListener(Event.COMPLETE, function(e:Event):void{
					var url:String = m_urlBySound[e.currentTarget as Sound];
					m_readySounds[url] = true;
				});
				
				m_sounds[sounds[i]] = sound;
			}
						
		}
		
		private static function onCooldownUp(te:TimerEvent):void{
			m_cooldownReady = true;
			m_cooldownTimer.stop();
		}
		
		private static var m_lastSoundPlayed:String;
		public static function play(path:String):void{
			if(m_cooldownReady || !(m_lastSoundPlayed == path)){
				m_lastSoundPlayed = path;
				m_cooldownReady = false;
				m_cooldownTimer.start();
				if(m_readySounds[path]){
					(m_sounds[path] as Sound).play();
				}				
			}

		}
	}
}